<?php

define('IN_DOUCO', true);
require (dirname(__FILE__) . '/include/init.php');
// rec操作项的初始化
$rec = $check->is_rec($_REQUEST['rec']) ? $_REQUEST['rec'] : 'config';
$act = $check->is_rec($_REQUEST['act']) ? $_REQUEST['act'] : 'default';

//获取直播频道缓存
$live_channels = $live->channel_list();
foreach($live_channels as $k=>$v) $live_channels_sort[$v['pullId']] = $v;
$smarty->assign('live_channels', $live_channels);
$smarty->assign('live_channels_sort', $live_channels_sort);
$smarty->assign('live_channels_json', json_encode($live_channels));
$smarty->assign('live_status_json', json_encode($_LANG['live_status_in']));

//print_r($live_channels);
//print_r($live->channel_info('f5c1fdea605f4f4ca8021a267ec4bad1'));

$smarty->assign('rec', $rec);
$smarty->assign('act', $act);
$smarty->assign('cur', 'live');
$smarty->assign('ur_here', $_LANG['live']);
$smarty->assign('anchor_link', array ('text' => $_LANG['anchor_list'],'href' => 'live.php?rec=default')); 
$smarty->assign('anchor_add_link', array ('text' => $_LANG['anchor_add'],'href' => 'live.php?rec=add')); 
$smarty->assign('live_set_link', array ('text' => $_LANG['live_set'],'href' => 'live.php?rec=config')); 
/**
 * +----------------------------------------------------------
 * 会员列表
 * +----------------------------------------------------------
 */
if ($rec == 'default') {
    //查看直播
    if($act == 'view_live'){
        if(isset($_REQUEST['pullid'])){
            $channel_info = $live->channel_info($_REQUEST['pullid']);
            $play_url = $channel_info['pullConfigureList'][0]['pullUrlList'][0]['originPullUrl'];
        }
        if(isset($_REQUEST['play_url'])) $play_url = urldecode($_REQUEST['play_url']);
        $smarty->assign('play_url', $play_url);
        $smarty->display('live_play.htm');
        exit;
    }
    $username = i('username','','request');
    $where = " WHERE 1 ";
    if($username){
        $where .= " AND username LIKE '%$username%' "; $get = "&username=$username";
    }
    //分页
    $page = $check->is_number($_REQUEST['page']) ? $_REQUEST['page'] : 1;
    $page_url = 'live.php?rec=default';
    $sql = "SELECT * FROM " . $dou->table('live_anchor')."$where ORDER BY id DESC";
    $limit = $dou->pager_sql($sql, 25, $page, $page_url, $get);
    $res = $dou->get_all($sql.$limit);
    foreach ($res as $k=>$row) {
        $anchor_list[$k] = $row;
        $anchor_list[$k]['create_time'] = date('Y-m-d H:i:s',$row['create_time']);
    }
    // 赋值给模板
    $smarty->assign('anchor_list', $anchor_list);
    $smarty->display('live.htm');
}

//添加
elseif ($rec == 'add') {
    $smarty->assign('token', $firewall->get_token());
    $smarty->display('live.htm');
}
elseif ($rec == 'insert') {
    data_filter();
    if (empty($_POST['password'])) $dou->dou_msg($_LANG['user_password'] . $_LANG['is_empty']);
    // CSRF防御令牌验证
    $firewall->check_token($_POST['token']);
    $post_data = array('username'=>$_POST['username'], 
        'nickname'=>$_POST['nickname'],
        'pullid'=>$_POST['pullid'],
        'channel'=>$_POST['channel'],
        'description'=>$_POST['description'], 
        'create_time'=>time()
    );
    if(!empty($_POST['password'])) $post_data['password'] = md5($_POST['password']);
    $sql = $dou->insert_sql('live_anchor', $post_data);
    $dou->query($sql);
    //操作记录
    $log_msg = $_LANG['user_edit'].': '.$_POST['username'];
    $dou->create_admin_log($log_msg);
    $dou->dou_msg($_LANG['add_succes'], 'live.php');
} 

//编辑
elseif ($rec == 'edit') {
    // 验证并获取合法的ID
    $id = $check->is_number($_REQUEST['id']) ? $_REQUEST['id'] : '';
    $anchor = $dou->get_row("SELECT * FROM ".$dou->table('live_anchor')." WHERE id='$id'");
    // CSRF防御令牌生成
    $smarty->assign('token', $firewall->get_token());
    $smarty->assign('anchor', $anchor);
    $smarty->display('live.htm');
}
elseif ($rec == 'update') {
    data_filter();
    // CSRF防御令牌验证
    $firewall->check_token($_POST['token']);
    $post_data = array('username'=>$_POST['username'], 
        'nickname'=>$_POST['nickname'],
        'pullid'=>$_POST['pullid'],
        'channel'=>$_POST['channel'],
        'description'=>$_POST['description']
    );
    if(!empty($_POST['password'])) $post_data['password'] = md5($_POST['password']);
    $sql = $dou->update_sql('live_anchor', $post_data, "id='{$_POST['id']}'");
    $dou->query($sql);
    //操作记录
    $log_msg = $_LANG['user_edit'].': '.$_POST['username'];
    $dou->create_admin_log($log_msg);
    $dou->dou_msg($_LANG['edit_succes'], 'live.php');
} 

//删除
elseif ($rec == 'del') {
    // 验证并获取合法的ID
    $id = $check->is_number($_REQUEST['id']) ? $_REQUEST['id'] : $dou->dou_msg($_LANG['illegal'], 'live.php');
    $username = $dou->get_one("SELECT username FROM " . $dou->table('live_anchor') . " WHERE id = '$id'");
    if (isset($_POST['confirm']) ? $_POST['confirm'] : '') {
        $dou->create_admin_log($_LANG['user_del'] . ': ' . $username);
        $dou->delete($dou->table('live_anchor'), "id = $id", 'live.php');
    } else {
        $_LANG['del_check'] = preg_replace('/d%/Ums', $username, $_LANG['del_check']);
        $dou->dou_msg($_LANG['del_check'], 'live.php', '', '30', "live.php?rec=del&id=$id");
    }
}

//批量操作选择
elseif ($rec == 'action') {
    if (is_array($_POST['checkbox'])) {
        if ($_POST['action'] == 'del_all') {//批量删除
            $dou->del_all('live_anchor', $_POST['checkbox'], 'id');
        } elseif($_POST['action'] == 'hide_all'){//批量隐藏
            $dou->update_all('live_anchor', $_POST['checkbox'], 'id', "status='hidden'");
        } else {
            $dou->dou_msg($_LANG['select_empty']);
        }
    } else {
        $dou->dou_msg($_LANG['record_select_empty']);
    }
}

//直播设置
elseif($rec == 'config'){
    $now = time();
    if(isset($_POST['submit']) && $_POST['room_id']>0) live_time_data($_POST['room_id']);
    $anchors = $dou->get_all("SELECT * FROM ".$dou->table('live_anchor')." ORDER BY id DESC");
    $rooms = $dou->get_all("SELECT * FROM ".$dou->table('chatroom')." ORDER BY id ASC");
    $room_id = !empty($_REQUEST['room_id']) ? $_REQUEST['room_id'] : $rooms[0]['id'];
    $room  = $dou->get_row("SELECT * FROM ".$dou->table('chatroom')." WHERE id='$room_id' ORDER BY id ASC");
    $res_livetime = $dou->get_all("SELECT la.state,la.pullid,lt.* FROM ".$dou->table('live_time')." lt ".
            " LEFT JOIN ".$dou->table('live_anchor')." la ON lt.anchor_id=la.id ".
            " WHERE lt.room_id='{$room_id}' ORDER BY lt.live_start ASC");
    foreach($res_livetime as $k=>$v){
        $livetime_arr[$k] = $v;
        $livetime_arr[$k]['state'] = ($v['state'] == '1' && (strtotime($v['live_start'])<=$now && strtotime($v['live_end'])>=$now)) ? '4' : $v['state'];
    }
    $room['live'] = $livetime_arr;
    $smarty->assign('rooms', $rooms);
    $smarty->assign('room', $room);
    $smarty->assign('anchors', $anchors);
    $smarty->assign('anchors_json', json_encode($anchors));
    $smarty->display('live.htm');
}

function data_filter(){
    global $dou,$_LANG;
    if (empty($_POST['username'])) $dou->dou_msg($_LANG['user_username'] . $_LANG['is_empty']);
    if (empty($_POST['nickname'])) $dou->dou_msg($_LANG['user_nickname'] . $_LANG['is_empty']);
    //if (empty($_POST['password'])) $dou->dou_msg($_LANG['user_password'] . $_LANG['is_empty']);
    $where = (isset($_POST['id']) && $_POST['id']>0) ? " AND id<>'{$_POST['id']}' " : '';
    $count = $dou->get_one("SELECT count(*) count FROM ".$dou->table('live_anchor')." WHERE pullid='{$_POST['pullid']}' $where");
    if($count > 0) $dou->dou_msg($_LANG['channel_has_use']);
    return true;
}

function live_time_data($room_id){
    global $dou;
    $insert_room_id = $room_id;
    //删除旧记录
    $dou->query($dou->delete_sql('live_time', "room_id='$insert_room_id'")); 
    //新增记录
    if($_POST['anchor_id']){
        foreach($_POST['anchor_id'] as $k=>$v){
            if(!empty($_POST['anchor_id'][$k]) && !empty($_POST['live_start'][$k])) {
                $_data = array('room_id'=>$insert_room_id, 
                    'anchor_id'   => $_POST['anchor_id'][$k], 
                    'live_start'  => $_POST['live_start'][$k], 
                    'live_end'    => $_POST['live_end'][$k],
                    'create_time' => time()
                );
                $dou->query($dou->insert_sql('live_time', $_data));
            }
        }
    }
}

?>